<template>
  <div>
    <el-tabs type="border-card" @tab-click="tabChange" v-model="activeName">
      <el-tab-pane v-for="tab in filteredTabs" :lazy="true" :name="tab.name" :label="tab.label" :key="tab.name">
      </el-tab-pane>
    </el-tabs>
    <router-view v-if="activity" :data="activity" :matchId="p.ID"></router-view>
  </div>
</template>

<script setup lang="ts">
import { TabPaneName, TabsPaneContext } from "element-plus";
import { computed, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { asyncTeamGetActivity, asyncgetteam } from "../../../api";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";

interface TabItem {
  name: TabPaneName;
  label: string;
  show: boolean | (() => boolean);
}

const allTabs: TabItem[] = [
  { name: '比赛成绩', label: '比赛成绩', show: true },
  { name: '比赛题目', label: '比赛题目', show: true },
  { name: '比赛总结', label: '比赛总结', show: true },
  { name: '比赛提交记录', label: '比赛提交记录', show: true },
  // {
  //   name: 'AI分析比赛', label: 'AI分析',
  //   show: () => showSummarize.value || showUserSummarize.value
  // },
];

const p = defineProps<{ ID: number }>()
const router = useRouter()
const route = useRoute()
const store = useStore(Storekey)
const user = computed(() => store.state.user)
const teamId = computed(() => user.value?.teamid)

const teamInfo = ref<Studycodemodel.Iteam | null>(null)
const showSummarize = computed(() => teamInfo.value?.other?.activitySummarize || false)
const showUserSummarize = computed(() => teamInfo.value?.other?.activityUserSummarize || false)

const filteredTabs = computed(() => {
  return allTabs.filter(tab => {
    if (typeof tab.show === 'function') return tab.show()
    return tab.show
  })
})

const activeName = ref<TabPaneName>(filteredTabs.value[0]?.name || '')

async function getteam() {
  teamInfo.value = await asyncgetteam({ ID: teamId.value })
}

watch(activeName, (name) => {
  router.push({ name: name.toString() })
})
function tabChange({ paneName: name }: TabsPaneContext) {
  if (!name) return
  activeName.value = name
}

const activity = ref<Studycodemodel.Iactivity>()
async function start() {
  if (p.ID) {
    const data = await asyncTeamGetActivity({ ID: p.ID, teamid: teamId.value })
    activity.value = data
  }

  if (route.name && filteredTabs.value.some(tab => tab.name === route.name)) {
    activeName.value = route.name as TabPaneName
  }
}

onMounted(async () => {
  await getteam()
  await start()

  // 确保当前激活的 tab 是可见的
  if (!filteredTabs.value.some(tab => tab.name === activeName.value)) {
    activeName.value = filteredTabs.value[0]?.name || ''
  }
})
</script>